package kz.pompei.ifacer.grot.acts;

import java.util.Iterator;
import java.util.LinkedList;

public class ActGroup extends Act {
  
  public final LinkedList<Act> group = new LinkedList<>();
  
  public ActGroup() {}
  
  @Override
  public void apply(GrotStorage grotStorage) throws Exception {
    for (Act act : group) {
      act.apply(grotStorage);
    }
  }
  
  @Override
  public void cancel(GrotStorage grotStorage) throws Exception {
    Iterator<Act> i = group.descendingIterator();
    while (i.hasNext()) {
      i.next().cancel(grotStorage);
    }
  }
  
  @Override
  public boolean canMerge(Act act) throws Exception {
    if (!(act instanceof ActGroup)) return false;
    ActGroup a = (ActGroup)act;
    int size = group.size();
    if (size != a.group.size()) return false;
    for (int i = 0; i < size; i++) {
      if (!(group.get(i).canMerge(a.group.get(i)))) return false;
    }
    return true;
  }
  
  @Override
  public void mergeAndApply(Act act, GrotStorage storage) throws Exception {
    ActGroup a = (ActGroup)act;
    int size = group.size();
    for (int i = 0; i < size; i++) {
      group.get(i).mergeAndApply(a.group.get(i), storage);
    }
  }
}
